package com.config.channels.service.impl;

import com.config.channels.entity.Version;
import com.config.channels.repository.VersionRepository;
import com.config.channels.service.VersionService;
import com.config.channels.utils.Cryptos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class VersionServiceImpl implements VersionService {

    @Autowired
    private VersionRepository versionRepository;

    @Autowired
    private StringRedisTemplate redisTemplate;
    private String keyPrefix = "version.";

    @Override
    public Version get(String version) {
        Version ver =  versionRepository.findByVersion(version);

        if(ver == null) {
            return versionRepository.findAll(new Sort(Sort.Direction.DESC,"version")).get(0);
        } else {
            return ver;
        }
    }

    public String getAesKey (String version) {
        String key = keyPrefix + version;
        String aesKey = null;
        ValueOperations<String, String> ops = this.redisTemplate.opsForValue();
        if(redisTemplate.hasKey(key)) {
            aesKey = ops.get(key);
        } else {
            Version ver = get(version);
            Cryptos cryptos = new Cryptos();
            aesKey = cryptos.aesDecrypt(ver.infos);
            ops.set(key,aesKey,3, TimeUnit.SECONDS);
        }
        return aesKey;
    }



    @Override
    public Version save(Version ver) {
        return versionRepository.save(ver);
    }
}
